# code:utf8
import logging
from datetime import datetime, timedelta
from zc_core.model.items import *
from zc_core.pipelines.helper.supplier_helper import SupplierHelper
from zc_core.util.common import parse_number, parse_time, parse_int
from pyquery import PyQuery
from zc_core.util.encrypt_util import short_uuid
from zc_core.util.sku_id_parser import convert_id2code

from szzfcg.matcher import match_cat_id, match_brand_id, match_supplier_id, match_total_page, match_sku_id

logger = logging.getLogger('rule')


# 解析catalog列表
def parse_catalog(response):
    jpy = PyQuery(response.text)
    nav1_txt_list = jpy('ul.menunav a')
    nav1_list = jpy('div#menucon > div')

    cats = list()
    for idx, nav1 in enumerate(nav1_list.items()):
        # 一级分类
        cat1_id = ''
        # 二级分类
        cat2_divs = nav1('div.line')
        for cat2_div in cat2_divs.items():
            cat2_a = cat2_div('em.z a')
            cat2_a('iconfont').remove()
            cat2_href = cat2_a.attr('href').strip()
            cat2_id = match_cat_id(cat2_href)
            # 截取一级分类编号
            if not cat1_id:
                cat1_id = cat2_id[0:3]
            cat2_name = cat2_a.text().strip()
            cat2 = _build_index_catalog(cat2_id, cat2_name, cat1_id, 2)
            cats.append(cat2)

            # 三级分类
            cat3_links = cat2_div('span.z a')
            for cat3_link in cat3_links.items():
                # 三级分类
                cat3_href = cat3_link.attr('href').strip()
                cat3_name = cat3_link.text().strip()
                cat3_id = match_cat_id(cat3_href)
                cat3 = _build_index_catalog(cat3_id, cat3_name, cat2_id, 3)
                cats.append(cat3)
        cat1_name = nav1_txt_list.eq(idx).text().strip()
        cat1 = _build_index_catalog(cat1_id, cat1_name, '', 1)
        cats.append(cat1)

    return cats


def _build_index_catalog(cat_id, cat_name, parent_id, level):
    cat = Catalog()
    cat['catalogId'] = str(cat_id)
    cat['catalogName'] = cat_name
    cat['parentId'] = parent_id
    cat['level'] = level
    if cat['level'] == 3:
        # 1、是
        cat['leafFlag'] = 1
    else:
        # 2、否
        cat['leafFlag'] = 2
    cat['linkable'] = 1

    return cat


# 解析brand列表
def parse_brand(response):
    jpy = PyQuery(response.text)
    brand_link_list = jpy('div#showBrandName li a')

    brands = list()
    for br in brand_link_list.items():
        brand = Brand()
        brand['id'] = match_brand_id(br.attr('onclick'))
        brand['name'] = br.text().strip()
        brands.append(brand)

    return brands


# 解析supplier列表
def parse_supplier(response):
    jpy = PyQuery(response.text)
    brand_link_list = jpy('span#suppliernamestyle li a')

    suppliers = list()
    for br in brand_link_list.items():
        supplier = Supplier()
        supplier['id'] = match_supplier_id(br.attr('onclick'))
        supplier['name'] = br.text().strip()
        supplier['batchNo'] = response.meta.get('batchNo')
        suppliers.append(supplier)

    return suppliers


# 解析总页数
def parse_total_page(response):
    jpy = PyQuery(response.text)
    last_link = jpy('div.pagation a:contains("尾页")')
    total = match_total_page(last_link.attr('onclick'))

    return int(total)


# 解析sku列表
def parse_sku(response):
    meta = response.meta
    batch_no = meta.get('batchNo')
    sp_helper = SupplierHelper()

    sku_list = list()
    jpy = PyQuery(response.text)
    skus = jpy('li.goodlist_li').items()
    for row in skus:
        link = row('div.goodlist_tit a').attr('href')
        sp_name = row('div.goodlist_item span.goodlist_logo').text()
        sale_price = row('div.goodlist_item span.goodlist_price').text()
        origin_price = row('div.goodlist_item del.goodlist_dmj').text()
        if origin_price:
            origin_price = origin_price.replace('店面价：', '')
        sold_count = row('div.goodlist_item span.goodlist_xl b').text()
        sku = Sku()
        sku['batchNo'] = batch_no
        sku['skuId'] = match_sku_id(link)
        sku['supplierId'] = sp_helper.get_id_by_name(sp_name)
        sku['salePrice'] = parse_number(sale_price)
        sku['originPrice'] = parse_number(origin_price, err=sku['salePrice'])
        sku['soldCount'] = parse_int(sold_count)
        sku_list.append(sku)

    return sku_list


# 解析ItemData
def parse_item_data(response):
    meta = response.meta
    jpy = PyQuery(response.text)
    result = ItemData()

    batch_no = meta.get('batchNo')
    sku_id = meta.get('skuId')

    nav = jpy('div.detailstop h2 a')
    sale_price = jpy('div.priceboxl span:eq(0) b').text().replace('元', '').strip()
    origin_price = jpy('div.priceboxl del').text().strip().replace('元', '').replace('店面价格', '')
    sold_amount = jpy('div.ljje_top span').text()
    sold_count = jpy('div.priceboxr span').text()

    detail = jpy('ul.detailsxx')
    gov_catalog = detail('li span:contains("品目：") + em')
    gov_catalog_name = gov_catalog('strong').text().replace('(', '').replace(')', '')
    gov_catalog('strong').remove()
    gov_catalog_id = gov_catalog.text()
    material_code = detail('li span:contains("条形码：") + em').text()
    supplier_sku_id = detail('li span:contains("商品编码：") + em').text()
    supplier_sku_link = detail('li span:contains("相关链接：") + a').attr('href')
    brand_name = detail('li span:contains("品牌：") + em').text()
    brand_model = detail('li span:contains("型号：") + em').text()
    on_sale_time = detail('li span:contains("更新时间：") + em').text()
    supplier_name = jpy('div.detailstopr_title span.item_logo').text()
    sku_name = jpy('div.detailstopr_title > b').attr('title')
    images = jpy('div#vertical > img')

    # -------------------------------------------------
    result['batchNo'] = batch_no
    result['skuId'] = sku_id
    if material_code:
        result['materialCode'] = material_code
    if not sku_name:
        sku_name = '__无标题__'
    result['skuName'] = sku_name.strip()
    if images:
        result['skuImg'] = images.eq(0).attr('src').strip()
    result['catalog1Id'] = match_cat_id(nav.eq(1).attr('href'))
    result['catalog1Name'] = nav.eq(1).text().strip()
    result['catalog2Id'] = match_cat_id(nav.eq(2).attr('href'))
    result['catalog2Name'] = nav.eq(2).text().strip()
    result['catalog3Id'] = match_cat_id(nav.eq(3).attr('href'))
    result['catalog3Name'] = nav.eq(3).text().strip()
    if gov_catalog_id:
        result['govCatId'] = gov_catalog_id.strip()
    if gov_catalog_name:
        result['govCatName'] = gov_catalog_name.strip()
    result['salePrice'] = parse_number(sale_price)
    result['originPrice'] = parse_number(origin_price, err=result['salePrice'])
    result['soldAmount'] = parse_number(sold_amount, 0)
    result['soldCount'] = parse_number(sold_count, 0)
    if brand_name and brand_name.strip():
        result['brandName'] = brand_name.strip()
    if supplier_name:
        result['supplierName'] = supplier_name.strip()
    if supplier_sku_id:
        result['supplierSkuId'] = supplier_sku_id.strip()
        plat_code = None
        if supplier_name and '得力' in supplier_name:
            plat_code = 'deli'
        result['supplierSkuCode'] = convert_id2code(plat_code, supplier_sku_id)

    if supplier_sku_link:
        result['supplierSkuLink'] = supplier_sku_link.strip()
    if brand_model:
        result['brandModel'] = brand_model.strip()
    if on_sale_time:
        result['onSaleTime'] = parse_time(on_sale_time)
    result['genTime'] = datetime.utcnow()
    # -------------------------------------------------

    same_trs = jpy('div.ljje_bom h3:contains("类似产品有售的商家：") + table tr')
    if same_trs and same_trs.size() > 1:
        # 商品种类编号（用于业务系统，多个同种类商品汇总展示）
        result['spuId'] = short_uuid()
        result['groupList'] = list()
        for idx in range(1, same_trs.size()):
            tr = same_trs.eq(idx)
            sku_id = match_sku_id(tr('td:eq(1) a').attr('href'))
            result['groupList'].append(sku_id)

    return result
